use proto::types::REQUEST;
use serde::Deserialize;

use crate::{AppErr, ErrConv};



#[derive(Debug)]
pub struct Frame {
    buf: Box<[u8]>
}

impl Frame {

    pub fn new(buf: Box<[u8]>) -> Frame {
        Frame { buf }
    }

    #[inline(always)]
    pub fn ts(&self) -> u8 {
        self.buf[0]
    }

    #[inline(always)]
    pub fn seq(&self) -> u8 {
        self.buf[1]
    }

    #[inline(always)]
    pub fn id(&self) -> u16 {
        ((self.ts() as u16) << 8) +
        (self.ts() as u16)
    }

    pub fn parse_connect<'a, T: Deserialize<'a>>(&'a self) -> Result<T, AppErr> {
        let data = serde_cbor::from_slice(&self.buf[2..]).conv()?;
        Ok(data)
    }

    pub fn parse_req<'a, T: Deserialize<'a>>(&'a self) -> Result<T, AppErr> {
        if self.buf.len() < 4 {
            return Err(AppErr::Invalid("无效的数据req_len < 4"));
        }
        let data = serde_cbor::from_slice(&self.buf[4..]).conv()?;
        Ok(data)
    }
}
